<template>
	<u-popup mode="bottom" v-model:show="show" :popup="false" :mask="true" :closeable="true" :safe-area-inset-bottom="true" close-icon-color="#ffffff" :maskCloseAble="true" @close="show=false">
		<view class="f px6 py8">
			<u-tag :type="i==index?'success':'info'" :class="{ml6:i>0}" :closeable="vs[i]>0" @close="close(i)" :text="item" v-for="(item, i) in tabs" :key="i" />
		</view>
		<view class="fjs h">
			<scroll-view :scroll-y="true" class="ht f1">
				<view class="p6 lh24" :class="{'fc-primary':vs[0]===item.value}" v-for="(item,i) in cates" :index="i" :key="i" @click="change(item.value)">
					{{item.label}}
				</view>
			</scroll-view>
			<scroll-view :scroll-y="true" class="ht f1" v-if="level>1 && v>0">
				<view class="p6 lh24" :class="{'fc-primary':vs[1]===item.value}" v-for="(item,i) in range[1]" :index="i" :key="i" @click="change(item.value)">
					{{item.label}}
				</view>
			</scroll-view>
			<scroll-view :scroll-y="true" class="ht f1" v-if="level>2 && v>100">
				<view class="p6 lh24" :class="{'fc-primary':vs[2]===item.value}" v-for="(item,i) in range[2]" :index="i" :key="i" @click="change(item.value)">
					{{item.label}}
				</view>
			</scroll-view>
		</view>
		<view class="p6" v-if="index+1>=min">
			<button type="primary" @click="confirm">确定</button>
		</view>
	</u-popup>
</template>

<script lang="ts">
import {mapState} from 'pinia'
import {cacheStore} from '@/store'

export default {
	props: {
		value: {
			type: Number,
			default: 0
		},
		level: {
			type: Number,
			default: 3
		},
		min: {
			type: Number,
			default: 1
		}
	},
	data() {
		return {
			show: false,
			vs: ['', '', ''],
			v: '' as string,
			range: [[], [], []],
			tabs: ['','',''],
			index: 0
		}
	},
	computed: mapState(cacheStore, ['cates']),
	methods: {
		change(v: string){
			this.v = v
			// this.vs = v > 0 ? v.toString().match(/\d{2}/g) : []
			this.index = v.length/2 - 1

			if(this.index<0) return
			this.vs[0] = v.substr(0,2)
			let item = this.cates.find((r: {value:string})=>this.vs[0])
			this.range[1] = item?.children ?? []
			this.tabs[0] = item?.label ?? '请选择'
			

			if(this.index<1) return
			this.vs[1] = v.substr(0,4)
			item = this.range[1].find((r: {value:string})=>r.value==this.vs[1])
			this.range[2] = item?.children ?? []
			this.tabs[1] = item?.label ?? "请选择"

			if(this.index<2) return
			this.vs[2] = v
			item = this.range[2].find((r: {value:string})=>r.value==v)
			this.tabs[2] = item?.label ?? "请选择"			
		},
		fresh(){
			
		},
		close(i){
			this.$set(this.vs, i, 0)
			if(i > 0 && this.index >= i){
				this.index = i - 1
			}
		},
		confirm(){
			this.$emit('update:value', this.vs.join(''))
			this.show=false
		}
	},
	mounted(){
		// console.log(this.range)
	},
	watch: {
		value(val: number){
			if(this.v !== val){
				this.change(val)
			}
		}
	}
}
</script>
<style scoped lang="scss">
	.h {height: 650rpx;}
</style>
